package com.pangus.ims.bs.testn9m;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Client  extends Thread{

    private static final Log logger = LogFactory.getLog(Client.class);
    //定义一个Socket对象
    Socket socket = null;

    public Client(String host, int port) {
        try {
            //需要服务器的IP地址和端口号，才能获得正确的Socket对象
            socket = new Socket(host, port);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        //客户端一连接就可以写数据给服务器了
        new sendMessThread().start();
        super.run();
        try {
            // 读Sock里面的数据
            InputStream in = socket.getInputStream();
           // while (true){
                if (in.available() != 0) {
                    int len = 0;
                    StringBuffer sb = new StringBuffer();
                    //读取四个字节
                    byte[] bytes = null;
                    bytes = new byte[12];
                    in.read(bytes);

                    sb.append(byte2decimal(bytes[0]));
                    sb.append(byte2decimal(bytes[1]));
                    sb.append(byte2decimal(bytes[2]));
                    sb.append(byte2decimal(bytes[3]));
                    String value = "";
                    for (int i = 0; i < bytes.length; i++) {
                        logger.info("第" + (i + 1) + "字节数据：" + bytes[i]);
                        String tString = Integer.toBinaryString((bytes[i] & 0xFF) + 0x100).substring(1);
                        logger.info("第" + (i + 1) + "字节二进制数据：" + tString);
                        value += tString;
                    }

                    logger.info("按字节读前12位二进制：" + value);
                    byte[] buf = new byte[1024];
                    while ((len = in.read(buf)) != -1) {
                        String jsonData = new String(buf, 0, len, "UTF-8");
                        logger.info("设备json数据内容:" + jsonData);
                        logger.info("设备json数据长度:" + jsonData.length());

                    }
                }
          //  }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 字节转二进制
     * @param b
     * @return
     */
    public static String byte2decimal(byte b){
        return Integer.toBinaryString((b & 0xFF) + 0x100).substring(1);
    }
    //往Socket里面写数据，需要新开一个线程
    class sendMessThread extends Thread{
        @Override
        public void run() {
            super.run();
            //写操作
            OutputStream os= null;
            OutputStreamWriter oWriter = null;
            try {
                os= socket.getOutputStream();
                oWriter = new OutputStreamWriter(os,"GBK");
                //登录数据
                // String testLogin = "{\"MODULE\":{\"HEAD\":{\"SITE\":\"0\",\"ID\":\"02\",\"DATA\":null,\"NAME\":null,\"CODE\":null,\"WORK\":\"sumin\",\"NUMBER\":\"super_admin\"}}}";
                //String testBarCode = "{\"MODULE\":{\"HEAD\":{\"SITE\":\"0\",\"ID\":\"01\",\"DATA\":\"\",\"NAME\":null,\"CODE\":\"G0219\",\"WORK\":\"sumin\",\"NUMBER\":\"123\"}}}";
                //   String testItem = "{\"MODULE\":{\"TEST\":{\"DATA\":{\"CONNAME\":\"C28\",\"TYPE\":\"\",\"SUBMODELS\":\"\",\"CHIP\":\"chip125\",\"IMEI1\":\"2345\",\"MAC\":\"\",\"VERSION\":\"\",\"TES_TIME\":\"65\"},\"RESULT\":[{\"ID\":\"01\",\"NAME\":\"版本号（固件/单片机）\",\"RESULT\":\"SUCCESS\"},{\"ID\":\"D8\",\"NAME\":\"加密授权\",\"RESULT\":\"SUCCESS\"},{\"ID\":\"A1\",\"NAME\":\"IR_CUT\",\"RESULT\":\"SUCCESS\"},{\"ID\":\"33\",\"NAME\":\"时间测试\",\"RESULT\":\"SUCCESS\"},{\"ID\":\"34\",\"NAME\":\"直通音视频\",\"RESULT\":\"SUCCESS\"},{\"ID\":\"E8\",\"NAME\":\"镜头长度写入\",\"RESULT\":\"SUCCESS\"},{\"ID\":\"15\",\"NAME\":\"获取温度\",\"RESULT\":\"SUCCESS\"},{\"ID\":\"0F\",\"NAME\":\"加密芯片获取\",\"RESULT\":\"SUCCESS\"},{\"ID\":\"DD\",\"NAME\":\"红外灯\",\"RESULT\":\"SUCCESS\"},{\"ID\":\"6D\",\"NAME\":\"光敏\",\"RESULT\":\"SUCCESS\"},{\"ID\":\"65\",\"NAME\":\"恢复出厂\",\"RESULT\":\"SUCCESS\"},{\"ID\":\"ED\",\"NAME\":\"结束测试\",\"RESULT\":\"SUCCESS\"}]},\"HEAD\":{\"SITE\":\"0\",\"ID\":\"99\",\"DATA\":\"\",\"NAME\":null,\"CODE\":\"G0221\",\"WORK\":\"sumin\",\"NUMBER\":\"123\"}}}";
                String testItem = "{\r\n" +
                        "  \"MODULE\": {\r\n" +
                        "    \"TEST\": {\r\n" +
                        "      \"DATA\": {\r\n" +
                        "        \"CONNAME\": \"A5-H1\",\r\n" +
                        "        \"TYPE\": \"\",\r\n" +
                        "        \"SUBMODELS\": \"\",\r\n" +
                        "        \"CHIP\": \"008802F6B4\",\r\n" +
                        "        \"IMEI1\": \"\",\r\n" +
                        "        \"IMEI2\": \"\"\r\n" +
                        "      },\r\n" +
                        "      \"RESULT\": [\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"01\",\r\n" +
                        "          \"NAME\": \"版本号（固件/单片机）\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"0F\",\r\n" +
                        "          \"NAME\": \"加密芯片号\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"09\",\r\n" +
                        "          \"NAME\": \"前置U口（U盘）\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"02\",\r\n" +
                        "          \"NAME\": \"RS232-1 \",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"03\",\r\n" +
                        "          \"NAME\": \"RS232-2\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"08\",\r\n" +
                        "          \"NAME\": \"RS485-1\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"05\",\r\n" +
                        "          \"NAME\": \"RS485-2\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"06\",\r\n" +
                        "          \"NAME\": \"CAN1\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"0B\",\r\n" +
                        "          \"NAME\": \"CAN2\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"0A\",\r\n" +
                        "          \"NAME\": \"内置SD卡1（双卡机SD1）\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"42\",\r\n" +
                        "          \"NAME\": \"贴片SD卡\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"38\",\r\n" +
                        "          \"NAME\": \"ACC惯量传感器\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"27\",\r\n" +
                        "          \"NAME\": \"车钥匙测试\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"14\",\r\n" +
                        "          \"NAME\": \"主板温度\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"10\",\r\n" +
                        "          \"NAME\": \"通讯模块1\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"25\",\r\n" +
                        "          \"NAME\": \"速度脉冲\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"26\",\r\n" +
                        "          \"NAME\": \"I/O输入（8路）\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"28\",\r\n" +
                        "          \"NAME\": \"I/O输出（out1/out2）\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"29\",\r\n" +
                        "          \"NAME\": \"电源输出（5V/5V/12V）\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"2D\",\r\n" +
                        "          \"NAME\": \"法拉电容/电池/电源输入\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"33\",\r\n" +
                        "          \"NAME\": \"RTC测试\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"37\",\r\n" +
                        "          \"NAME\": \"MAC地址导入\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"20\",\r\n" +
                        "          \"NAME\": \"喊话器按键+前面板遥控\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"21\",\r\n" +
                        "          \"NAME\": \"车内喇叭\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"22\",\r\n" +
                        "          \"NAME\": \"车外喇叭\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"34\",\r\n" +
                        "          \"NAME\": \"直通音视频\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"23\",\r\n" +
                        "          \"NAME\": \"前面板LED/LCD\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"24\",\r\n" +
                        "          \"NAME\": \"风扇（整机）\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        },\r\n" +
                        "        {\r\n" +
                        "          \"ID\": \"35\",\r\n" +
                        "          \"NAME\": \"法拉电容\",\r\n" +
                        "          \"RESULT\": \"PASS\"\r\n" +
                        "        }\r\n" +
                        "      ]\r\n" +
                        "    },\r\n" +
                        "    \"HEAD\": {\r\n" +
                        "      \"SITE\": \"0\",\r\n" +
                        "      \"ID\": \"99\",\r\n" +
                        "      \"DATA\": \"\",\r\n" +
                        "      \"NAME\": null,\r\n" +
                        "      \"CODE\": \"WM210303410000121233\",\r\n" +
                        "      \"WORK\": \"sumin\",\r\n" +
                        "      \"NUMBER\": \"super_admin\"\r\n" +
                        "    }\r\n" +
                        "  }\r\n" +
                        "}";
                oWriter.write(testItem);
                oWriter.flush();

                InputStream inputStream = socket.getInputStream();
                byte[] b = new byte[20480];
                inputStream.read(b);
                String msgString = new String(b,"GBK").trim();
                System.out.println(msgString+"======");
                inputStream.close();
                oWriter.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String getdate() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String result = format.format(date);
        return result;
    }

    //函数入口
    public static void main(String[] args) {
        //需要服务器的正确的IP地址和端口号
//        Client clientTest=new Client("10.21.2.24", 8881);
//
//        clientTest.start();


        for (int i=0;i<10;i++){
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Client clientTest=new Client("10.21.10.5", 5556);
            clientTest.start();
        }




    }


    public static byte[] bitString2ByteArray2(String bitString) {
        int size = bitString.length() / 8;
        byte[] bytes = new byte[size];

        for (int i = 0, total = 0; i < size; i++) {
            byte b = 0x00;
            for (int j = 0; j < 8; j++, total++) {
                b |= (byte) ((bitString.charAt(total) - 48) << (7 - j));
            }
            bytes[i] = b;
        }
        return bytes;
    }



    public static byte[] byteMerger(byte[] byte_1, byte[] byte_2){
        byte[] byte_3 = new byte[byte_1.length+byte_2.length];
        System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);
        System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);
        return byte_3;
    }
}
